<script setup lang="ts">
import { computed, reactive, watch } from 'vue';
import { useLoading } from '@sa/hooks';
import {
  fetchCreateCustomerService,
  fetchUpdateCustomerService,
} from '@/service/api/business/customer-service';
import { uploadFile } from '@/service/api/business/system-config';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';

defineOptions({
  name: 'CustomerServiceOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.Business.CustomerService | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { createRequiredRule } = useFormRules();
const { loading: submitLoading, startLoading: startSubmitLoading, endLoading: endSubmitLoading } = useLoading();
const { loading: uploadLoading, startLoading: startUploadLoading, endLoading: endUploadLoading } = useLoading();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增客服配置',
    edit: '编辑客服配置'
  };
  return titles[props.operateType];
});

type Model = Api.Business.CustomerServiceOperateParams;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    remark: '',
    img: '',
    wechatCode: '',
    status: 0
  };
}

type RuleKey = Extract<keyof Model, 'img' | 'wechatCode' | 'status'>;

const rules: Record<RuleKey, App.Global.FormRule | App.Global.FormRule[]> = {
  img: createRequiredRule('图片不能为空'),
  wechatCode: createRequiredRule('微信号不能为空'),
  status: createRequiredRule('状态不能为空')
};

// 文件上传处理
async function handleFileUpload(event: Event, field: keyof Model) {
  const input = event.target as HTMLInputElement;
  if (!input.files || input.files.length === 0) return;

  const file = input.files[0];
  startUploadLoading();

  try {
    const { error, data } = await uploadFile(file);
    if (!error && data) {
      model[field] = data.fileUrl;
      window.$message?.success('图片上传成功');
    } else {
      window.$message?.error('图片上传失败');
    }
  } catch (error) {
    console.error('图片上传错误:', error);
    window.$message?.error('图片上传失败');
  } finally {
    endUploadLoading();
    input.value = ''; // 清空文件选择
  }
}

// 触发文件选择
function triggerFileInput(field: keyof Model) {
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = 'image/*'; // 只允许选择图片文件
  input.onchange = (event) => handleFileUpload(event, field);
  input.click();
}

// 查看图片
function viewImage(imageUrl: string) {
  if (imageUrl) {
    window.open(imageUrl, '_blank');
  }
}

// 删除图片
function removeImage(field: keyof Model) {
  model[field] = '';
}

function handleUpdateModelWhenEdit() {
  if (props.operateType === 'add') {
    Object.assign(model, createDefaultModel());
    return;
  }

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();
  startSubmitLoading();

  try {
    if (props.operateType === 'add') {
      const { error } = await fetchCreateCustomerService(model);
      if (error) return;
    }

    if (props.operateType === 'edit') {
      const { error } = await fetchUpdateCustomerService(model);
      if (error) return;
    }

    window.$message?.success($t('common.updateSuccess'));
    closeDrawer();
    emit('submitted');
  } catch (error) {
    console.error('操作失败:', error);
  } finally {
    endSubmitLoading();
  }
}

watch(visible, () => {
  if (visible.value) {
    handleUpdateModelWhenEdit();
    restoreValidation();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" :title="title" display-directive="show" :width="500" class="max-w-90%">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NDivider>客服信息</NDivider>

        <!-- 图片上传 -->
        <NFormItem label="客服图片" path="img">
          <div class="flex flex-col gap-3">
            <div class="flex items-center gap-2">
              <NButton @click="triggerFileInput('img')" :loading="uploadLoading">
                选择图片
              </NButton>
              <span v-if="model.img" class="text-green-600">已上传</span>
              <NButton v-if="model.img" text @click="viewImage(model.img)" type="primary">
                查看
              </NButton>
              <NButton v-if="model.img" text @click="removeImage('img')" type="error">
                删除
              </NButton>
            </div>
            <div v-if="model.img" class="mt-2">

            </div>
          </div>
        </NFormItem>

        <NFormItem label="微信号" path="wechatCode">
          <NInput v-model:value="model.wechatCode" placeholder="请输入微信号" />
        </NFormItem>

        <NFormItem label="备注信息" path="remark">
          <NInput v-model:value="model.remark" type="textarea" placeholder="请输入备注信息" />
        </NFormItem>

        <NFormItem label="启用状态" path="status">
          <DictRadio v-model:value="model.status" dict-code="sys_normal_disable" />
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" :loading="submitLoading" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped>
.flex-center {
  display: flex;
  align-items: center;
  gap: 4px;
}
</style>
